{%extends "base.html"%}
{%block head%}
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<style>
    .problem-meta {
        padding-bottom: 30px;
        word-wrap: break-all;
    }
</style>
<script src="/static/ace/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/ace/ext-language_tools.js" type="text/javascript" charset="utf-8"></script>

{%endblock%}
{%block body%}

<!-- <script src="/static/vue2-ace.js"></script> -->
<script>
    let problem;
    Vue.component("editor", {
        delimiters: ['{[', ']}'],
        render: function (h) {
            var height = this.height ? this.px(this.height) : '100%'
            var width = this.width ? this.px(this.width) : '100%'
            return h('div', {
                attrs: {
                    style: "height: " + height + '; width: ' + width,
                }
            })
        },
        props: {
            value: {
                type: String,
                required: true
            },
            lang: String,
            theme: String,
            height: true,
            width: true,
            options: Object
        },
        data: function () {
            return {
                editor: null,
                contentBackup: ""
            }
        },
        methods: {
            px: function (n) {
                if (/^\d*$/.test(n)) {
                    return n + "px";
                }
                return n;
            }
        },
        watch: {
            value: function (val) {
                if (this.contentBackup !== val) {
                    this.editor.session.setValue(val, 1);
                    this.contentBackup = val;
                }
            },
            theme: function (newTheme) {
                this.editor.setTheme('ace/theme/' + newTheme);
            },
            lang: function (newLang) {
                this.editor.getSession().setMode('ace/mode/' + newLang);
            },
            options: function (newOption) {
                this.editor.setOptions(newOption);
            },
            height: function () {
                this.$nextTick(function () {
                    this.editor.resize()
                })
            },
            width: function () {
                this.$nextTick(function () {
                    this.editor.resize()
                })
            }
        },
        beforeDestroy: function () {
            this.editor.destroy();
            this.editor.container.remove();
        },
        mounted: function () {
            var vm = this;
            var lang = this.lang || 'text';
            var theme = this.theme || 'chrome';

            // require('brace/ext/emmet');

            var editor = vm.editor = ace.edit(this.$el);
            this.$emit('init', editor);

            editor.$blockScrolling = Infinity;
            //editor.setOption("enableEmmet", true);
            editor.getSession().setMode('ace/mode/' + lang);
            editor.setTheme('ace/theme/' + theme);
            editor.setValue(this.value, 1);
            this.contentBackup = this.value;
            editor.setFontSize(18);
            editor.setOption("wrap", "free");
            ace.require("ace/ext/language_tools");
            editor.setOptions({
                enableBasicAutocompletion: true,
                enableSnippets: true,
                enableLiveAutocompletion: true
            });
            editor.on('change', function () {
                var content = editor.getValue();
                vm.$emit('input', content);
                vm.contentBackup = content;
            });
            if (vm.options)
                editor.setOptions(vm.options);
        }
    });
    $(document).ready(() => {
        // ace.require("ace/ext/language_tools");
        problem = new Vue({
            el: "#show-problem",
            delimiters: ['{[', ']}'],
            mixins: [baseMixin],
            data: {
                problemData: {},
                userData: {},
                selectedLanguage: "",
                selectedAccount: "",
                code: "",
                done: false,
                running: false,
                message: "",
                errorMessage: "",
                captcha: {
                    login: "", submit: ""
                },
                requireLoginCaptcha: false,
                requireSubmitCaptcha: false,
                captchaData: {
                    login: "", submit: ""
                },
                isContest: false,
                contestID: -1,
                contestProblemID: -1
            },
            mounted() {
                let problem_id = window.location.pathname.split("/").pop();
                // let contestID, contestProblemID;
                if (problem_id === "contest_problem") {
                    let args = getRequest();
                    this.contestID = parseInt(args["contest_id"]);
                    this.contestProblemID = parseInt(args["contest_problem_id"]);
                    console.log(this.contestID, this.contestProblemID);
                    problem_id = -1;
                }
                axios.post("/api/remote_judge/get_problem_info", { problem_id: problem_id, contest_id: this.contestID, contest_problem_id: this.contestProblemID }).then(resp => {
                    let data = resp.data;
                    if (data.code) {
                        showErrorModal(data.message);
                        return;
                    }
                    data = data.data;
                    this.problemData = data.problemData;
                    this.userData = data.userData;
                    this.selectedLanguage = data.userData.lastLanguage;
                    this.code = data.userData.lastCode;
                    this.selectedAccount = Object.keys(this.userData.accounts)[0];
                    this.isContest = data.isContest;
                    $("title").text(this.problemData.title + " - " + this.problemData.id + " - {{APP_NAME}}");
                    this.done = true;
                    console.log(data);
                });
            },
            methods: {
                submit: function () {
                    this.running = true;
                    let submitData = {
                        problemID: this.problemData.id,
                        remoteAccountID: this.selectedAccount,
                        code: this.code,
                        loginCaptcha: this.captcha.login,
                        submitCaptcha: this.captcha.submit,
                        language: this.selectedLanguage,
                        contestID: this.contestID,
                        contestProblemID: this.contestProblemID
                    };
                    this.requireLoginCaptcha = this.requireSubmitCaptcha = false;
                    this.errorMessage = "";
                    console.log(submitData);
                    let socket = io.connect("/ws/remote_judge");
                    socket.on("message", resp => {
                        this.message = resp.message;
                        console.log("message: ", resp)
                    });
                    socket.on("server_response", resp => {
                        this.running = false;
                        let data = resp.data;
                        if (data.require_login_captcha) {
                            this.captcha.login = "";
                            this.captchaData.login = data.captcha;
                            this.requireLoginCaptcha = true;
                        }
                        if (data.require_submit_captcha) {
                            this.captcha.submit = "";
                            this.captchaData.submit = data.captcha;
                            this.requireSubmitCaptcha = true;
                        }
                        console.log("server response: ", resp);
                        if (resp.ok) {
                            window.location.href = "/show_submission/" + resp.data.submission_id;
                        } else {
                            this.errorMessage = data.message;
                        }
                    });
                    socket.emit("submit", submitData);
                },
                removeProblem() {
                    $("#warning-modal").modal({
                        onApprove: () => {
                            $.post("/api/problem/remove", { problem_id: this.problemData.id }).done(ctx => {
                                ctx = JSON.parse(ctx);
                                if (ctx.code) {
                                    showErrorModal(ctx.message);
                                    return;
                                }
                                window.location.href = "/";
                            })
                        },
                        closable: false
                    }).modal("show");
                }
            }
        });
        Vue.component("problem-meta", {
            delimiters: ['{[', ']}'],
            data() {
                return {
                    htmlContent: ""
                }
            },
            template: '<div class="ui container problem-meta"  v-if="value!=\'\'"><div class="ui fluid two column grid"><div class="ui column">\
                            <div class="ui header"><h3>{[name]}</h3></div></div><div class="ui right aligned column">\
                                <div class="ui tiny orange circular icon button" @click="copyText(value)"><i class="clipboard outline icon"></i></div>\
                                    </div></div>    <div class="ui stack segment"><div  v-html="htmlContent" v-if="!usePre"></div><pre v-html="htmlContent" style="white-space:pre-wrap;word-break:break-word;" v-else></pre>    </div></div>',
            props: {
                //内容
                value: {
                    type: String, default: ""
                }, name: {
                    //显示名
                    type: String, default: ""
                }, renderMarkdown: {
                    //是否渲染Markdown
                    type: Boolean, default: true
                }, usePre: {
                    //是否使用预格式化块
                    type: Boolean, default: false
                }
            },
            methods: {
                copyText: copy_text
            }, mounted() {
                // const converter = new showdown.Converter();
                if (this.renderMarkdown)
                    this.htmlContent = converter.makeHtml(this.value);
                else {
                    this.htmlContent = this.value;
                }
            }
        });



    });

</script>
<div style="top:10%;max-width: 700px;">

    <div id="show-problem" v-if="done">

        <div class="ui header">
            <h1> {[problemData.id]}: {[problemData.title]} </h1>
        </div>

        <problem-meta name="题目背景" v-bind:value="problemData.background"></problem-meta>
        <problem-meta name="题目内容" v-bind:value="problemData.content"></problem-meta>
        <problem-meta name="输入格式" v-bind:value="problemData.input_format"></problem-meta>
        <problem-meta name="输出格式" v-bind:value="problemData.output_format"></problem-meta>
        <div class="ui two column grid" v-for="item,index in problemData.examples">
            <div class="ui column">
                <problem-meta v-bind:name="'样例 '+(index+1)+' 输入'" v-bind:value="item.input" :render-markdown="false"
                    :use-pre="true">
                </problem-meta>
            </div>
            <div class="ui column">
                <problem-meta v-bind:name="'样例 '+(index+1)+' 输出'" v-bind:value="item.output" :render-markdown="false"
                    :use-pre="true">
                </problem-meta>
            </div>
        </div>

        <problem-meta name="提示" v-bind:value="problemData.hint"></problem-meta>
        <div class="ui container problem-meta">
            <div class="ui header">
                <h3>提交代码</h3>
            </div>
            <div class="ui one column grid">
                <div class="ui column">
                    <div class="ui two column grid" style="min-height: 500px;">
                        <div class="ui four wide column">
                            <div class="ui vertical pointing menu"
                                style="overflow-y: scroll;height:500px; max-width: 170px; overflow-x: hidden">
                                <a class="item" v-for="value,key in problemData.remoteOJ.availableLanguages"
                                    v-bind:class="{active:selectedLanguage==key}" @click="selectedLanguage=key">
                                    <span>
                                        <span class="ui header">
                                            <h4>{[value.display]}</h4>
                                        </span>
                                    </span>
                                    <!-- <p></p> -->
                                </a>
                            </div>
                        </div>
                        <div class="twelve wide stretched column" style="padding-left: 0;">
                            <div class="ui container">
                                <editor v-model="code"
                                    v-bind:lang="problemData.remoteOJ.availableLanguages[selectedLanguage].aceMode"
                                    theme="github" style="left:30px;min-height: 500px;">
                                </editor>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="ui one column grid">
                <div class="ui column">
                    <div class="ui center aligned container" style="margin-top: 30px;">
                        <div class="ui compact menu" v-if="Object.keys(userData.accounts).length">
                            <div class="ui simple dropdown item">
                                {[userData.accounts[selectedAccount].oj]} -
                                {[userData.accounts[selectedAccount].username]}
                                <i class="dropdown icon"></i>
                                <div class="menu">
                                    <a class="item" v-for="value,key in userData.accounts"
                                        v-on:click="selectedAccount=key">
                                        {[value.oj]} - {[value.username]}
                                    </a>
                                </div>
                            </div>
                            <div class="ui icon green button" @click="submit" v-bind:class="{loading:running}">
                                <i class="paper plane outline icon"></i>
                                提交！
                            </div>
                        </div>
                        <div v-else>
                            <div class="ui error message">
                                <p>您还未添加任何远程评测账户!</p>
                                <p>请在个人资料编辑中添加.</p>
                            </div>
                        </div>

                    </div>
                </div>
                <div class="ui column">
                    <div class="ui error message" v-if="errorMessage!=''">
                        <div class="ui header">错误</div>
                        <p>{[errorMessage]}</p>
                    </div>
                    <div class="ui segment stacked" v-if="requireLoginCaptcha">
                        <div class="ui header">
                            <h3>请输入登录验证码</h3>
                        </div>
                        <div><img :src="'data:image/png;base64,'+captchaData.login">
                            <div class="ui input"><input type="text" v-model="captcha.login"></div>

                        </div>
                    </div>

                    <div class="ui segment stacked" v-if="requireSubmitCaptcha">
                        <div class="ui header">
                            <h3>请输入登录验证码</h3>
                        </div>
                        <div><img :src="'data:image/png;base64,'+captchaData.submit">
                            <div class="ui input"><input type="text" v-model="captcha.submit"></div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="ui " style="position: fixed;margin-left:750px;margin-top:100px;top:50px;">
            <div class="ui segment stacked" style="max-width: 300px">
                <table class="ui very basic fluid collapsing celled table">

                    <tbody>
                        <tr v-if="!isContest">
                            <td>题目上传者</td>
                            <td style="word-break: break-all;"><a
                                    :href="'/profile/'+problemData.uploaderProfile.uid">{[problemData.uploaderProfile.username]}</a>
                            </td>
                        </tr>
                        <tr v-if="!isContest">
                            <td>上传时间</td>
                            <td style="word-break: break-all;">{[problemData.createTime]}</td>
                        </tr>

                        <tr v-if="!isContest">
                            <td>是否公开</td>
                            <td>{[problemData.public?"Yes":"No"]}</td>
                        </tr>
                        <tr v-if="!isContest">
                            <td>我的提交</td>
                            <td>
                                <div v-if="userData.id==-1">尚未提交</div><a v-else :href="'/show_submission/'+userData.id"
                                    target="_blank">
                                    <judge-status :status="userData.status"></judge-status>
                                </a>
                            </td>
                        </tr>
                        <tr v-if="!isContest">
                            <td>通过数/提交数/通过率</td>
                            <td>{[problemData.acceptedCount]}/{[problemData.submissionCount]}/{[parseInt(100*problemData.acceptedCount/problemData.submissionCount)]}%
                            </td>
                        </tr>

                        <tr>
                            <td>评测方式</td>
                            <td>远程评测: {[problemData.remoteOJ.display]}</td>
                        </tr>
                        <tr v-if="!isContest">
                            <td>远程题目ID</td>
                            <td>{[problemData.remoteProblemID]}</td>
                        </tr>

                    </tbody>
                </table>
                <a :href="'/problem_edit/'+problemData.id"
                    v-if="!isContest&&(base.uid==problemData.uploaderProfile.uid||userData.managable)"
                    target="_blank">编辑</a>
                <a v-on:click="removeProblem"
                    v-if="!isContest&&(base.uid==problemData.uploaderProfile.uid||userData.managable)">删除</a>
                <a :href="'/submissions/1?filter=uid%3D'+base.uid+'%2Cproblem%3D'+problemData.id" target="_blank"
                    v-if="!isContest">我的提交</a>
                <a :href="'/submissions/1?filter=problem%3D'+problemData.id" target="_blank" v-if="!isContest">全部提交</a>
                <a :href="'/submissions/1?filter=status%3Daccepted%2Cproblem%3D'+problemData.id" target="_blank"
                    v-if="!isContest">通过提交</a>



            </div>
            <div class="ui stack segment" style="max-width: 300px" v-if="!isContest">
                <div class="ui header">
                    <h4>讨论</h4>
                </div>
                <table class="ui very basic fluid collapsing celled table"
                    v-if="problemData.recentDiscussions.length!=0">
                    <tbody>
                        <tr v-for="item in problemData.recentDiscussions">
                            <td>
                                <a :href="'/show_discussion/'+item.id" target="_blank">{[item.title]}</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div v-else>无</div>
                <a :href="'/discussions/discussion.problem.'+problemData.id+'/1'" target="_blank">查看更多..</a>
            </div>
        </div>
    </div>
    <div class="ui basic modal" id="no-perm-modal">
        <div class="ui icon header">
            <i class="error icon"></i>
            错误
        </div>
        <div class="content">
            <div class="ui center aligned container">
                <p id="no-perm-text"></p>
            </div>
        </div>
        <div class="actions">
            <div class="ui green ok inverted button" onclick="window.location.href='/'">
                <i class="checkmark icon"></i>
                返回主页
            </div>
        </div>
    </div>
</div>
<div class="ui modal" id="warning-modal">
    <div class="ui header">
        警告
    </div>
    <div class="content">
        <p>删除题目会发生以下后果</p>
        <p>1.所有关于该题目的提交会被删除</p>
        <p>2.所有现在正在使用该题目的比赛将会无法正常访问</p>
    </div>
    <div class="actions">
        <div class="ui green approve button">
            确定
        </div>
        <div class="ui blue cancel button">
            取消
        </div>
    </div>
</div>
{%endblock%}